import React, { useState, useEffect } from 'react'
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Row,
  Col,
  Typography,
  Descriptions
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  BookOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { Option } = Select
const { TextArea } = Input

// 状态枚举
const STATUS = {
  ENABLED: 1, // 启用
  DISABLED: 0 // 禁用
}

const Index = ({ selectedDictType, onBack }) => {
  const [dictData, setDictData] = useState([])
  const [modalVisible, setModalVisible] = useState(false)
  const [editingData, setEditingData] = useState(null)
  const [form] = Form.useForm()

  // 模拟字典数据
  const mockDictData = {
    user_status: [
      {
        id: 1,
        dictType: 'user_status',
        label: '正常',
        value: '1',
        sort: 1,
        status: STATUS.ENABLED,
        description: '用户正常状态',
        createTime: '2023-01-15 11:00:00'
      },
      {
        id: 2,
        dictType: 'user_status',
        label: '禁用',
        value: '0',
        sort: 2,
        status: STATUS.ENABLED,
        description: '用户被禁用',
        createTime: '2023-01-15 11:05:00'
      },
      {
        id: 3,
        dictType: 'user_status',
        label: '锁定',
        value: '2',
        sort: 3,
        status: STATUS.ENABLED,
        description: '用户被锁定',
        createTime: '2023-01-16 09:30:00'
      }
    ],
    gender: [
      {
        id: 4,
        dictType: 'gender',
        label: '男',
        value: '1',
        sort: 1,
        status: STATUS.ENABLED,
        description: '男性',
        createTime: '2023-02-10 10:00:00'
      },
      {
        id: 5,
        dictType: 'gender',
        label: '女',
        value: '2',
        sort: 2,
        status: STATUS.ENABLED,
        description: '女性',
        createTime: '2023-02-10 10:05:00'
      },
      {
        id: 6,
        dictType: 'gender',
        label: '未知',
        value: '0',
        sort: 3,
        status: STATUS.ENABLED,
        description: '性别未知',
        createTime: '2023-02-10 10:10:00'
      }
    ],
    order_status: [
      {
        id: 7,
        dictType: 'order_status',
        label: '待支付',
        value: '1',
        sort: 1,
        status: STATUS.ENABLED,
        description: '订单等待支付',
        createTime: '2023-03-20 15:00:00'
      },
      {
        id: 8,
        dictType: 'order_status',
        label: '已支付',
        value: '2',
        sort: 2,
        status: STATUS.ENABLED,
        description: '订单已支付',
        createTime: '2023-03-20 15:05:00'
      },
      {
        id: 9,
        dictType: 'order_status',
        label: '已完成',
        value: '3',
        sort: 3,
        status: STATUS.ENABLED,
        description: '订单已完成',
        createTime: '2023-03-20 15:10:00'
      }
    ],
    notice_type: [
      {
        id: 10,
        dictType: 'notice_type',
        label: '系统通知',
        value: '1',
        sort: 1,
        status: STATUS.ENABLED,
        description: '系统通知',
        createTime: '2023-04-05 11:30:00'
      },
      {
        id: 11,
        dictType: 'notice_type',
        label: '业务通知',
        value: '2',
        sort: 2,
        status: STATUS.ENABLED,
        description: '业务通知',
        createTime: '2023-04-05 11:35:00'
      }
    ]
  }

  // 获取状态文本
  const getStatusText = status => {
    return status === STATUS.ENABLED ? '启用' : '禁用'
  }

  // 获取状态颜色
  const getStatusColor = status => {
    return status === STATUS.ENABLED ? 'green' : 'red'
  }

  // 字典数据表格列
  const columns = [
    {
      title: '字典标签',
      dataIndex: 'label',
      key: 'label',
      render: text => <span style={{ fontWeight: 500 }}>{text}</span>
    },
    {
      title: '字典键值',
      dataIndex: 'value',
      key: 'value',
      render: text => <Tag color='blue'>{text}</Tag>
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size='middle'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => handleEditData(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title='确定要删除这个字典项吗？'
            onConfirm={() => handleDeleteData(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 加载字典数据
  useEffect(() => {
    if (selectedDictType) {
      const data = mockDictData[selectedDictType.type] || []
      setDictData(data)
    }
  }, [selectedDictType])

  // 添加字典数据
  const handleAddData = () => {
    setEditingData(null)
    form.resetFields()
    form.setFieldsValue({
      dictType: selectedDictType.type,
      sort: 1,
      status: STATUS.ENABLED
    })
    setModalVisible(true)
  }

  // 编辑字典数据
  const handleEditData = data => {
    setEditingData(data)
    form.setFieldsValue(data)
    setModalVisible(true)
  }

  // 删除字典数据
  const handleDeleteData = id => {
    setDictData(dictData.filter(item => item.id !== id))
    message.success('字典项删除成功')
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingData) {
      // 编辑
      setDictData(
        dictData.map(item =>
          item.id === editingData.id ? { ...item, ...values } : item
        )
      )
      message.success('字典项更新成功')
    } else {
      // 新增
      const newData = {
        id: Math.max(...dictData.map(d => d.id), 0) + 1,
        ...values,
        createTime: new Date().toLocaleString()
      }
      setDictData([...dictData, newData])
      message.success('字典项创建成功')
    }
    setModalVisible(false)
  }

  if (!selectedDictType) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
          <BookOutlined style={{ fontSize: 48, marginBottom: 16 }} />
          <div>请选择字典类型查看数据</div>
        </div>
      </Card>
    )
  }

  return (
    <Card>
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between'
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            {selectedDictType.name}
            <Tag color='blue' style={{ marginLeft: 12 }}>
              {selectedDictType.type}
            </Tag>
          </Title>
          <div style={{ color: '#666', fontSize: '14px' }}>
            {selectedDictType.description}
          </div>
        </div>
        <Space>
          <Button icon={<PlusOutlined />} onClick={handleAddData}>
            新增字典项
          </Button>
          <Button icon={<ReloadOutlined />} onClick={onBack}>
            返回
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={dictData}
        rowKey='id'
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true
        }}
      />

      {/* 字典数据模态框 */}
      <Modal
        title={editingData ? '编辑字典项' : '新增字典项'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Form.Item name='dictType' label='字典类型'>
            <Input disabled />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='label'
                label='字典标签'
                rules={[{ required: true, message: '请输入字典标签' }]}
              >
                <Input placeholder='请输入字典标签' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='value'
                label='字典键值'
                rules={[{ required: true, message: '请输入字典键值' }]}
              >
                <Input placeholder='请输入字典键值' />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='sort'
                label='排序'
                rules={[{ required: true, message: '请输入排序号' }]}
              >
                <InputNumber min={1} max={999} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name='status' label='状态' valuePropName='checked'>
                <Switch
                  checkedChildren='启用'
                  unCheckedChildren='禁用'
                  defaultChecked
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name='description' label='描述'>
            <TextArea rows={3} placeholder='请输入字典项描述' />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingData ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}

export default Index
